package com.angel.controller;

import java.util.*;

import javax.annotation.Resource;

import com.angel.bean.Branches;
import com.angel.bean.Employee;
import com.angel.bean.EmployeeType;
import com.angel.dto.EmployeeDto;
import com.angel.dtoutlis.EmployeeDtoUtil;
import com.angel.exception.StatusException;
import com.angel.service.BranchesService;
import com.angel.service.EmployeeService;
import com.angel.service.EmployeeTypeService;
import com.angel.service.OtherlogService;
import com.angel.shiro.SystemAdminAuthorizingRealm;
import com.angel.utils.AdminUserUtils;
import com.angel.utils.LogUtils;
import com.angel.utils.NoUtlis;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/employeeController")
public class EmployeeController {

    @Resource
    private EmployeeService employeeService;

    @Resource
    private EmployeeTypeService employeeTypeService;

    @Resource
    private BranchesService branchesService;

    @Autowired
    private OtherlogService otherlogService;

    /**
     * 添加员工
     *
     * @return 重定向所有员工
     * @RequiresPermissions("user") 权限控制器必须登录才能访问
     */
    @RequestMapping("/addEmployee")
    @ResponseBody
    public Object addEmployee(Employee employee) {
        Map<Object, Object> map = new HashMap<Object, Object>();

        // branchesId 分店id
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        int branchesId = principal.getEmployee().getBranchesId();
        Employee et =principal.getEmployee();

        employee.setBranchesId(branchesId);

        // 必须要有分店编号，性别、岗位类型
        employee.setEmNo(NoUtlis.getEpNo(employee));

        // loginName 登录名默认电话号码
        employee.setLoginName(employee.getEmTel());

        // state 账号状态：默认未删除
        employee.setState(1);

        int result = employeeService.insertSelective(employee);
        String msg ="添加员工，登录账户为："+employee.getLoginName();
        if (result != 0) {
            msg += "成功";
            map.put("result", "success");
        }else {
            msg +="失败";
        }
        LogUtils.InsertLog(et,otherlogService,msg);
        return map;
    }

    /***
     * 更新员工信息
     *
     * @RequiresPermissions("user") 权限控制器必须登录才能访问@RequiresPermissions("user")
     * @param employee 前端传入emId值
     * @return
     */
    @RequestMapping("/updateEmployee")
    @ResponseBody
    public Object updateEmployee(Employee employee) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        String msg ="更新员工信息：员工id:"+employee.getEmId();
        int result = employeeService.update(employee);
        if (result != 0) {
            msg+="成功";
            map.put("result", "success");
        }
        LogUtils.InsertLog(et,otherlogService,msg);
        return map;
    }

    /***
     * 删除员工信息
     *
     * @RequiresPermissions("user") 权限控制器必须登录才能访问
     * @param employee 前端传入emId值
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping("/deleteEmployee")
    @ResponseBody
    public Object deleteEmployee(Employee employee) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        String msg ="删除员工信息:id"+employee.getEmId();
        int result = employeeService.delete(employee);
        if (result != 0) {
            msg+="成功";
            map.put("result", "success");
        }
        LogUtils.InsertLog(et,otherlogService,msg);
        return map;
    }

    /**
     * 查询单个员工信息
     *
     * @return
     * @RequiresPermissions("user") 权限控制器必须登录才能访问
     */
    @RequiresPermissions("user")
    @RequestMapping("/findOneEmployee")
    @ResponseBody
    public Object findOneEmployee(Employee employee) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        System.out.println("------------------------------------进入获得员工控制层");
        Employee emp = employeeService.findOne(employee);

        map.put("emp", emp);

        return map;
    }

    /**
     * 查询所有员工类型
     *
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping("/findEmployeeType")
    @ResponseBody
    public Object findEmployeeType(EmployeeType employeeType) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        employeeType.setState(1);

        List<EmployeeType> employeeTypeList = employeeTypeService.findEmployeeType(employeeType);

        List<EmployeeType> tmplist = new ArrayList<EmployeeType>();
        for (EmployeeType empt : employeeTypeList){
            if (et.getEmTypeId()< empt.getEmTypeId()){
                tmplist.add(empt);
            }
        }

        if (employeeTypeList != null) {
            map.put("employeeTypeList", tmplist);
        }

        return map;
    }

    /**
     * 查询分店信息
     *
     * @return
     */
    @RequestMapping("/findBranches")
    @ResponseBody
    public Object findBranches(Branches branches) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        branches.setState(1);

        List<Branches> branchesList = branchesService.findAll(branches);
        if (branchesList != null) {
            map.put("branchesList", branchesList);
        }
        return map;
    }

    /**
     * 根据分店查询员工信息
     */
    @RequestMapping("/findbrEmployee")
    @ExceptionHandler(value = StatusException.class)
    public String findBranchEmployee(@RequestParam(value = "pn", defaultValue = "1") String pn,@RequestParam("branch") String branch, Model model) {

        //将前端传回的参数改为String类型，然后进行数据类型转换，如果出现问题，则进行异常处理，异常可以是空处理
        Integer branchId = null;
        int pageNo = 1;
        try {
            pageNo = Integer.valueOf(pn);
            branchId = Integer.valueOf(branch);
        } catch (Exception e) {
            return "redirect:/index";
        }
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        if (et.getEmTypeId() > 2 || et.getBranchesId() != 1){
            return "redirect:/index";
        }
        Branches branches = new Branches();
        branches.setBranId(branchId);
        branches  = branchesService.findOneBranches(branches);
        model.addAttribute("branch",branches);
        //在查询之前传入当前页，然后多少记录
        PageHelper.startPage(pageNo, 10);

        Employee employee = new Employee();
        employee.setState(1);
        employee.setBranchesId(branchId);
        List<Employee> employeeList = employeeService.findEmployee(employee);
        EmployeeType employeeType = new EmployeeType();
        employeeType.setState(1);
        List<EmployeeType> employeeTypeList = employeeTypeService.findEmployeeType(employeeType);

        PageInfo pageInfo = new PageInfo(employeeList);
        List<EmployeeDto> dtoList = EmployeeDtoUtil.getEmployeeDto(pageInfo.getList(), employeeTypeList);
        pageInfo.setList(dtoList);
        if (pageInfo != null) {
            model.addAttribute("pageInfo", pageInfo);
        }
        return "branchemployeeEntry";
    }



    /**
     * 查询员工信息
     *
     * @return
     * @RequiresPermissions("user") 权限控制器必须登录才能访问
     */
    @RequiresPermissions("user")
    @RequestMapping("/findEmployee")
    @ExceptionHandler(value = StatusException.class)
    public String findEmployee(@RequestParam(value = "pn", defaultValue = "1") String pn, Model model) {

        //将前端传回的参数改为String类型，然后进行数据类型转换，如果出现问题，则进行异常处理，异常可以是空处理
        int pageNo = 1;
        try {
            pageNo = Integer.valueOf(pn);
        } catch (Exception e) {

        }
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        //在查询之前传入当前页，然后多少记录
        PageHelper.startPage(pageNo, 10);

        Employee employee = new Employee();
        employee.setState(1);
        if (et.getBranchesId() !=1){
            employee.setBranchesId(et.getBranchesId());
        }
        List<Employee> employeeList = employeeService.findEmployee(employee);
        EmployeeType employeeType = new EmployeeType();
        employeeType.setState(1);
        List<EmployeeType> employeeTypeList = employeeTypeService.findEmployeeType(employeeType);

        PageInfo pageInfo = new PageInfo(employeeList);
        List<EmployeeDto> dtoList = EmployeeDtoUtil.getEmployeeDto(pageInfo.getList(), employeeTypeList);
        pageInfo.setList(dtoList);

        if (pageInfo != null) {
            model.addAttribute("pageInfo", pageInfo);
        }
        return "employeeEntry";
    }

    /**
     * 模糊查询
     *
     * @param pn
     * @param model
     * @return
     */
    @RequestMapping("/searchEmployee")
    @ExceptionHandler(value = StatusException.class)
    public String searchEmployee(@RequestParam(value = "pn", defaultValue = "1") String pn,
                                 @RequestParam(value = "type") String type,
                                 @RequestParam(value = "content") String content,
                                 Model model) {
        int pageNo = 1;
        try {
            pageNo = Integer.valueOf(pn);
        } catch (Exception e) {

        }
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        content = content.trim().replaceAll(" ", "");
        PageHelper.startPage(pageNo, 5);
        Employee employee;
        employee = new Employee();
        if (et.getEmTypeId() !=1){
            employee.setBranchesId(et.getBranchesId());
        }
        List<Employee> employeeList = null;
        switch (type) {
            case "emNo":
                // 工号
                employee.setEmNo(content);
                employeeList = employeeService.searchEmployee(employee);
                break;
            case "emName":
                // 姓名
                employee.setEmName(content);
                employeeList = employeeService.searchEmployee(employee);
                break;
            case "emTel":
                // 电话
                employee.setEmTel(content);
                employeeList = employeeService.searchEmployee(employee);
                break;
            case "loginName":
                // 登录名
                employee.setLoginName(content);
                employeeList = employeeService.searchEmployee(employee);
                break;
            default:
                break;
        }
        PageInfo pageInfo = new PageInfo(employeeList);
        EmployeeType employeeType = new EmployeeType();
        employeeType.setState(1);
        List<EmployeeType> employeeTypeList = employeeTypeService.findEmployeeType(employeeType);
        List<EmployeeDto> dtoList = EmployeeDtoUtil.getEmployeeDto(pageInfo.getList(), employeeTypeList);
        pageInfo.setList(dtoList);

        model.addAttribute("type", type);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("content", content);
        return "employeeEntry2";
    }
}
